package com.outsourcing.bottle.ui;

import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.PlatformAccountTable;
import com.outsourcing.bottle.db.StickersPackTable;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.PasterDirConfigEntry;
import com.outsourcing.bottle.domain.PlatformAccount;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class BindRegisterActivity extends BasicActivity implements BasicUIEvent, OnClickListener, Callback {
	
	private final int bind_success = 2; 
	private final int bind_error = 3;
	private final int bind_register = 4;
	
	private ImageView platformView;
	private TextView nickNameTextView;
	private TextView platformTextView;
	
	private EditText accountView;
	private EditText emailView;
	private RadioGroup sexView;
	private EditText passwordView;
	private EditText repasswordView;
	private Button bindView;
	private Button hasAccountView;
	private ImageView close;
	
	private String platform;
	private String openuid;
	
	private PlatformAccount platformAccount;
	
	private String account;
	private String email;
	private String password;
	private String repassword;
	private int sex;
	private String deviceId;
	
	private Handler handler;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setContentView(R.layout.bind_register);
		try {
			platform = getIntent().getStringExtra("platform");
			openuid = getIntent().getStringExtra("openuid");
			PlatformAccountTable pat = new PlatformAccountTable();
			if (TextUtil.notEmpty(platform) && TextUtil.notEmpty(openuid)) {
				platformAccount = pat.getPlatformAccount(PlatformBindConfig.getOpenType(platform), openuid);
			}
			initWidget();
			TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
			deviceId = tm.getDeviceId();
//			LocationThread lt = new LocationThread(basicHandler, locationManager);
//			lt.start();
			//网络定位
			networkLocat();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initWidget() {
		platformView = (ImageView) findViewById(R.id.bind_register_platform);
		nickNameTextView = (TextView) findViewById(R.id.bind_register_nickname);
		if (platformAccount != null) {
			nickNameTextView.setVisibility(View.VISIBLE);
			nickNameTextView.setText(getString(R.string.login_txt_hello) + "," + platformAccount.getNickName());
		}
		platformTextView = (TextView) findViewById(R.id.bind_register_platform_text);
		accountView = (EditText) findViewById(R.id.bind_register_account);
		emailView = (EditText) findViewById(R.id.bind_register_email);
		bindView = (Button) findViewById(R.id.bind_register_bind);
		bindView.setOnClickListener(this);
		hasAccountView = (Button) findViewById(R.id.bind_register_havaaccount);
		hasAccountView.setOnClickListener(this);
		sexView = (RadioGroup) findViewById(R.id.bind_register_radioGroup);
//		maleView = (RadioButton) findViewById(R.id.bind_register_male);
//		femaleView = (RadioButton) findViewById(R.id.bind_register_female);
		passwordView = (EditText) findViewById(R.id.bind_register_password);
		repasswordView = (EditText) findViewById(R.id.bind_register_repassword);
		repasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					checkRegister();
				}
				return false;
			}
		});
		close = (ImageView) findViewById(R.id.close);
		close.setOnClickListener(this);
		if (TextUtil.notEmpty(platform)) {
			hasAccountView.setVisibility(View.VISIBLE);
			bindView.setVisibility(View.VISIBLE);
			platformView.setVisibility(View.VISIBLE);
			nickNameTextView.setVisibility(View.VISIBLE);
			if (platform.equals(PlatformBindConfig.Sina)) {
				platformView.setBackgroundResource(R.drawable.ico_weibo);
				platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_weibo));
			} else if (platform.equals(PlatformBindConfig.Douban)) {
				platformView.setBackgroundResource(R.drawable.ico_douban);
				platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_douban));
			} else if (platform.equals(PlatformBindConfig.Tencent)) {
				platformView.setBackgroundResource(R.drawable.ico_tqq);
				platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_tencent));
			} else if (platform.equals(PlatformBindConfig.QQ)) {
				platformView.setBackgroundResource(R.drawable.ico_qq);
				platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_qq));
			} else if (platform.equals(PlatformBindConfig.Renren)) {
				platformView.setBackgroundResource(R.drawable.ico_renren);
				platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_renren));
			} else if (platform.equals(PlatformBindConfig.Twitter)) {
				platformView.setBackgroundResource(R.drawable.ico_twitter);
				platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_twitter));
			} else {
				platformView.setBackgroundResource(R.drawable.ico_facebook);
				platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_facebook));
			}
		} else {
			hasAccountView.setVisibility(View.GONE);
			bindView.setText(getString(R.string.login_txt_register));
			platformView.setVisibility(View.GONE);
			nickNameTextView.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		if (v == bindView) {
			checkRegister();
		} else if (v == hasAccountView) {
			Intent register = new Intent(BindRegisterActivity.this, BindLoginActivity.class);
			register.putExtra("platform", platform);
			register.putExtra("openuid", openuid);
			startActivity(register);
		} else if (v == close) {
			finish();
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case bind_register:
			bindRegister();
			break;
		default:
			break;
		}
	}
	
	private void checkRegister() {
		account = accountView.getText().toString().trim();
		email = emailView.getText().toString().trim();
		int buttonId = sexView.getCheckedRadioButtonId();
		password = passwordView.getText().toString().trim();
		repassword = repasswordView.getText().toString().trim();
		if (account.equals("")) {
			onToast(getString(R.string.login_txt_register_error_account));
			return;
		} 
		if (email.equals("")) {
			onToast(getString(R.string.login_txt_reset_error));
			return;
		} else if (!TextUtil.isValidEmail(email)) {
			onToast(getString(R.string.login_txt_register_error_email));
			return;
		}
		if (buttonId == -1) {
			onToast(getString(R.string.login_txt_register_error_sex));
			return;
		}
		if (password.equals("")) {
			onToast(getString(R.string.login_txt_error_pwd_tips));
			return;
		} else if (password.length() < 6) {
			onToast(getString(R.string.login_txt_error_pwd_not_enough));
			return;
		}
		if (!password.equals(repassword)) {
			onToast(getString(R.string.login_txt_error_pwd_not_same));
			return;
		}
		if (sexView.getCheckedRadioButtonId() == R.id.bind_register_male) {
			sex = 1;
		} else if (sexView.getCheckedRadioButtonId() == R.id.bind_register_female) {
			sex = 2;
		} else {
			sex = 0;
		}
		UICore.eventTask(this, this, bind_register, getString(R.string.init_data), null);
	}
	
	private void bindRegister() {
		try {
			String url = UrlConfig.bind_register;
			HashMap<String, String> paramMaps = new HashMap<String, String>();
			paramMaps.put("username", account);
			paramMaps.put("password", password);
			paramMaps.put("email", email);
			paramMaps.put("sex", String.valueOf(sex));
			if (platformAccount != null) {
				paramMaps.put("open_type", String.valueOf(platformAccount.getOpenType()));
				paramMaps.put("access_token", platformAccount.getAccessToken());
				paramMaps.put("token_secret", platformAccount.getTokenSecret());
				paramMaps.put("nickname", platformAccount.getNickName());
				paramMaps.put("open_uid", platformAccount.getOpenUid());
				paramMaps.put("open_sex", String.valueOf(platformAccount.getOpenSex()));
				paramMaps.put("open_expire", platformAccount.getOpenExpire());
				paramMaps.put("open_avatar", platformAccount.getOpenAvatar());
			}
			paramMaps.put("device_token", deviceId);
			paramMaps.put("device_type", android.os.Build.MODEL);
			paramMaps.put("device_provider", android.os.Build.PRODUCT);
			paramMaps.put("device_version", android.os.Build.VERSION.RELEASE);
			paramMaps.put("lat", String.valueOf(AppContext.getInstance().getLatitude()));
			paramMaps.put("lng", String.valueOf(AppContext.getInstance().getLongitude()));
			if (countryIso != null && countryIso.equalsIgnoreCase("cn")) {
				paramMaps.put("location_mode", "1");
			} else {
				paramMaps.put("location_mode", "0");
			}
			String result = HttpUtils.doPost(this, url, paramMaps);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				int login_uid = resultObj.getInt("login_uid");
				if (login_uid != 0) {
					String login_token = resultObj.getString("login_token");
					AppContext.getInstance().setLogin_uid(login_uid);
					AppContext.getInstance().setLogin_token(login_token);
					SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
					Editor editor = preferences.edit();
					editor.putInt("login_uid", login_uid);
					editor.putString("login_token", login_token);
					editor.commit();
					
					try {
						getLoginUserStickers();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					handler.sendEmptyMessage(bind_success);
				} else {
					String errmsg = resultObj.getString("errmsg");
					Message message = Message.obtain(handler, bind_error, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case bind_success:
//			Intent intent = new Intent(BindRegisterActivity.this, HomeActivity.class);
//			startActivity(intent);
			Intent intent = new Intent(BindRegisterActivity.this, RegisterSuccessActivity.class);
			startActivity(intent);
			BindRegisterActivity.this.finish();
			break;
		case bind_error:
			onToast((String) msg.obj);
			break;
		default:
			break;
		}
		return false;
	}
	
	/**
	 * 获取贴纸目录
	 */
	private void getLoginUserStickers() {
		StickersPackTable stickPackTable = new StickersPackTable();
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		ServiceUtils.dout("login url:" + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result,
					LoginUserInfo.class);
			/*********** 保存贴纸目录路径 *********/
			List<PasterDirConfigEntry> pasterdir_config = loginUserInfo
					.getPasterdir_privs_list();
			stickPackTable.clearTalbe();
			for (PasterDirConfigEntry mPasterDirEntry : pasterdir_config) {
				stickPackTable.saveStickDir(mPasterDirEntry);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
